package bit.lotterysystem.service.impl;

import bit.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import bit.lotterysystem.common.exception.ServiceException;
import bit.lotterysystem.common.utils.JWTUtil;
import bit.lotterysystem.common.utils.RegexUtil;
import bit.lotterysystem.controller.param.ShortMessageLoginParam;
import bit.lotterysystem.controller.param.UserLoginParam;
import bit.lotterysystem.controller.param.UserPasswordLoginParam;
import bit.lotterysystem.controller.param.UserRegisterParam;
import bit.lotterysystem.dao.dataobject.Encrypt;
import bit.lotterysystem.dao.dataobject.UserDO;
import bit.lotterysystem.dao.mapper.UserMapper;
import bit.lotterysystem.service.UserService;
import bit.lotterysystem.service.VerificationCodeService;
import bit.lotterysystem.service.dto.UserDTO;
import bit.lotterysystem.service.dto.UserLoginDTO;
import bit.lotterysystem.service.dto.UserRegisterDTO;
import bit.lotterysystem.service.enums.UserIdentityEnum;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.util.StringUtils;

import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Override
    public UserRegisterDTO register(UserRegisterParam param) {
        //校验注册信息
        checkRegisterInfo(param);

        //加密私密数据（构造Dao层请求）
        UserDO userDO=new UserDO();
        userDO.setUserName(param.getName());
        userDO.setEmail(param.getMail());
        userDO.setPhoneNumber(new Encrypt(param.getPhoneNumber()));
        userDO.setIdentity(param.getIdentity());
        if(StringUtils.hasText(param.getPassword())){
            userDO.setPassword(DigestUtil.sha256Hex(param.getPassword()));
        }

        //保存数据
        userMapper.insert(userDO);
        //构造返回
        UserRegisterDTO userRegisterDTO = new UserRegisterDTO();
        userRegisterDTO.setUserId(12L);
        return userRegisterDTO;
    }

    @Override
    public UserLoginDTO login(UserLoginParam param) {
        UserLoginDTO userLoginDTO;
        //类型转换与检查，Java14及以上版本同时做到类型检查与转换
        if(param instanceof UserPasswordLoginParam loginParam){
            userLoginDTO=loginByUserPassword(loginParam);
        }else if(param instanceof ShortMessageLoginParam loginParam){
            userLoginDTO=loginByShortMessage(loginParam);
        }else{
            throw new ServiceException(ServiceErrorCodeConstants.LOGIN_INFO_NOT_EXIST);
        }
        return userLoginDTO;
    }

    //identity可能为空
    @Override
    public List<UserDTO> findUserInfo(UserIdentityEnum identity) {
        String identityString=identity==null?null:identity.name();
        //查表
        List<UserDO> userDOList=userMapper.selectUserListByIdentity(identityString);
        List<UserDTO> userDTOList=userDOList.stream().map(
                userDO -> {
                    UserDTO userDTO=new UserDTO();
                    userDTO.setId(userDO.getId());
                    userDTO.setUserName(userDO.getUserName());
                    userDTO.setEmail(userDO.getEmail());
                    userDTO.setPhoneNumber(userDO.getPhoneNumber().getValue());
                    userDTO.setIdentity(UserIdentityEnum.forName(userDO.getIdentity()));
                    return userDTO;
                }).collect(Collectors.toList());

        return userDTOList;
    }

    private UserLoginDTO loginByShortMessage(ShortMessageLoginParam loginParam) {
        if(RegexUtil.checkMobile(loginParam.getLoginMobile())){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //获取用户数据
        UserDO userDO = userMapper.selectByPhoneNumber(new Encrypt(loginParam.getLoginMobile()));
        if(userDO==null){
            throw new ServiceException(ServiceErrorCodeConstants.USER_INFO_IS_EMPTY);
        }else if(StringUtils.hasText(loginParam.getMandatoryIdentity())
        &&loginParam.getMandatoryIdentity().equalsIgnoreCase(userDO.getIdentity())){
            throw new ServiceException(ServiceErrorCodeConstants.IDENTITY_ERROR);
        }
        //校验验证码
        String code=verificationCodeService.getVerificationCode(loginParam.getLoginMobile());
        if(!loginParam.getVerificationCode().equals(code)){
            throw new ServiceException(ServiceErrorCodeConstants.VERIFICATION_CODE_ERROR);
        }
        //塞入返回值
        Map<String,Object> claim=new HashMap<>();
        claim.put("id",userDO);
        claim.put("identity",userDO.getIdentity());
        String token=JWTUtil.genJwt(claim);

        UserLoginDTO userLoginDTO=new UserLoginDTO();
        userLoginDTO.setToken(token);
        userLoginDTO.setIdentity(UserIdentityEnum.forName(userDO.getIdentity()));
        return userLoginDTO;

    }

    private UserLoginDTO loginByUserPassword(UserPasswordLoginParam loginParam) {
        UserDO userDO=null;
        //判断手机登录还是邮箱登录
        if(RegexUtil.checkMail(loginParam.getLoginName())){
            //查询用户表
             userDO=userMapper.selectByMail(loginParam.getLoginName());
        }else if(RegexUtil.checkMobile(loginParam.getLoginName())){
            //查询用户表
            userDO=userMapper.selectByPhoneNumber(new Encrypt(loginParam.getLoginName()));
        }else{
            throw new ServiceException(ServiceErrorCodeConstants.LOGIN_NOT_EXIST);
        }

        //校验登录信息
        if(userDO==null){
            throw new ServiceException(ServiceErrorCodeConstants.USER_INFO_IS_EMPTY);
        }else if(StringUtils.hasText(loginParam.getMandatoryIdentity())
                &&!loginParam.getMandatoryIdentity().equalsIgnoreCase(userDO.getIdentity())){
            //强制身份登录，身份校验不通过
            throw new ServiceException(ServiceErrorCodeConstants.IDENTITY_ERROR);
        } else if(!DigestUtil.sha256Hex(loginParam.getPassword()).equals(userDO.getPassword())){
            //校验密码不同
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_ERROR);
        }

        //塞入返回值
        Map<String,Object> claim=new HashMap<>();
        claim.put("id",userDO);
        claim.put("identity",userDO.getIdentity());
        String token=JWTUtil.genJwt(claim);

        UserLoginDTO userLoginDTO=new UserLoginDTO();
        userLoginDTO.setToken(token);
        userLoginDTO.setIdentity(UserIdentityEnum.forName(userDO.getIdentity()));
        return userLoginDTO;
    }

    private void checkRegisterInfo(UserRegisterParam param) {
        if (param == null) {
            throw new ServiceException(ServiceErrorCodeConstants.REGISTER_INFO_IS_EMPTY);
        }
       //校验邮箱格式
         if(!RegexUtil.checkMail(param.getMail())){
             throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
         }
        //校验手机号格式
        if(!RegexUtil.checkMobile(param.getPhoneNumber())){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        //校验身份信息
       if(UserIdentityEnum.forName(param.getIdentity())==null){
           throw new ServiceException(ServiceErrorCodeConstants.IDENTITY_ERROR);
       }

        //校验管理员密码必填
        if(param.getIdentity().equalsIgnoreCase(UserIdentityEnum.ADMIN.name())
        && !StringUtils.hasText(param.getPassword())){
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_IS_EMPTY);
        }

        //密码校验，大于等于6位
        if(StringUtils.hasText(param.getPassword())&&!RegexUtil.checkPassword(param.getPassword())){
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_ERROR);
        }

        //校验邮箱是否被使用
        if(cheakMailUsed(param.getMail())){
            throw new ServiceException(ServiceErrorCodeConstants.MIAL_USED);
        }

        //校验手机号是否被使用
        if(checkPhoneNumberUse(param.getPhoneNumber())){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_USED);
        }
    }

    private boolean checkPhoneNumberUse(String phoneNumber) {
        int count=userMapper.countByPhone(new Encrypt(phoneNumber));
        return count>0;
    }

    private boolean cheakMailUsed(String mail){
        int count = userMapper.countByMail(mail);
        return count>0;
    }
}
